package com.share.dubbo.es.manager.impl;

import com.share.common.common.Page;
import com.share.dubbo.es.manager.EsJavaLogManager;
import com.share.dubbo.es.model.EsJavaLogReq;
import com.share.dubbo.es.model.EsJavaLogResq;
import com.share.dubbo.es.model.EsJavaLogSaveReq;
import com.share.es.model.enums.EsEnum;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * @author 01401061 - 孙艳强
 * @date 2020/10/27 19:05
 */
@Slf4j
@Service
public class EsJavaLogManagerImpl implements EsJavaLogManager {
    private EsEnum esEnum = EsEnum.JAVA_LOG;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /*需求总量统计*/
    @PostConstruct
    public void aa111() {
        count(new EsJavaLogReq());
    }
    @Override
    public Long count(EsJavaLogReq req) {
        /*设置索引库和文档*/
        SearchRequest searchRequest = new SearchRequest(esEnum.getIndex());
        searchRequest.searchType(esEnum.getType());

        /*构建查询条件*/
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        if (!StringUtils.isEmpty(req.getIp())) {
            sourceBuilder.query(QueryBuilders.termQuery("host", req.getIp()));//等值条件设定
        }

//        AbstractAggregationBuilder valueCountAggregationBuilder = AggregationBuilders.count("count").field("host");
//        sourceBuilder.aggregations().addAggregator(valueCountAggregationBuilder); /*count计数*/

        log.info("普通查询的DSL语句:" + sourceBuilder.toString());
        searchRequest.source(sourceBuilder);

        //执行查询
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Page<EsJavaLogResq> pageList(EsJavaLogReq req) {
        return null;
    }

    @Override
    public Long save(EsJavaLogSaveReq req) {
        return 1L;
    }
}
